var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var _limitMenu = system.MENULIMIT.STOCK06;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'stock/data/list_analysis';
var _height = $(parent).height()-298,_width = $(parent).width()-192;

var Utils = {
	doQueryDepot : function(){
		commonDia = $.dialog({
			title : '选择仓库',
			content : 'url:'+config.BASEPATH+'base/depot/to_list_dialog_bymodule',
			data : {multiselect:false,module:'stock'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#depot_code").val(selected.dp_code);
				$("#depot_name").val(selected.dp_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#depot_code").val(selected.dp_code);
					$("#depot_name").val(selected.dp_name);
				}
			},
			cancel:true
		});
	},
	doQueryBrand : function(){
		commonDia = $.dialog({
			title : '选择品牌',
			content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].bd_code);
					names.push(selected[i].bd_name);
				}
				$("#bd_code").val(codes.join(","));
				$("#bd_name").val(names.join(","));
			},
			close:function(){
			},
			cancel:true
		});
	},
	doQueryType : function(){
		commonDia = $.dialog({
			title : '选择类别',
			content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
			data : {multiselect:true},
			width : 300,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].tp_code);
					names.push(selected[i].tp_name);
				}
				$("#tp_code").val(codes.join(","));
				$("#tp_name").val(names.join(","));
			},
			close:function(){
			},
			cancel:true
		});
	},
	doQueryProduct : function(){
		commonDia = $.dialog({
			title : '选择商品',
			content : 'url:'+config.BASEPATH+'base/product/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#pd_code").val(selected.pd_code);
				$("#pd_name").val(selected.pd_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#pd_code").val(selected.pd_code);
					$("#pd_name").val(selected.pd_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	formatRealAmount:function(val, opt, row){
		return row.in_amount-row.out_amount;
	},
	formatRealMoney:function(val, opt, row){
		return PriceLimit.formatMoney(row.in_money-row.out_money);
	},
	formatReturnRate:function(val, opt, row){
		if(row.in_amount == 0){
			return "0.00";
		}
		return PriceLimit.formatMoney(row.out_amount/row.in_amount*100);
	},
	formatMoneyProportion:function(val, opt, row){
		if(val == "合计"){
			return "";
		}
		var userData = $("#grid").getGridParam('userData');
		if(userData.in_money-userData.out_money == 0){
			return "0.00";
		}
		return PriceLimit.formatMoney((row.in_money-row.out_money)/(userData.in_money-userData.out_money)*100);
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.initSeason();
		this.initYear();
	},
	initSeason:function(){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"base/dict/list?dtl_upcode=KEY_SEASON",
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.data != "" && data.data.length > 0){
					var seasons = data.data;
					seasons.unshift({dtl_code:"",dtl_name:"全部"});
					$('#span_pd_season').combo({
						value : 'dtl_code',
						text : 'dtl_name',
						width : 207,
						listHeight : 300,
						listId : '',
						defaultSelected : 0,
						editable : false,
						callback : {
							onChange : function(data) {
								if(data.dtl_code != ""){
									$("#pd_season").val(data.dtl_name);
								}else{
									$("#pd_season").val("");
								}
							}
						}
					}).getCombo().loadData(seasons,["dtl_name",$("#pd_season").val(),0]);
				}
			}
		 });
	},
	initYear:function(){
		var currentYear = new Date().getFullYear();
		var data = [
		    {Code:"",Name:"全部"},
			{Code:""+parseInt(currentYear+1)+"",Name:""+parseInt(currentYear+1)+""},
			{Code:""+parseInt(currentYear)+"",Name:""+parseInt(currentYear)+""},
			{Code:""+parseInt(currentYear-1)+"",Name:""+parseInt(currentYear-1)+""},
			{Code:""+parseInt(currentYear-2)+"",Name:""+parseInt(currentYear-2)+""},
			{Code:""+parseInt(currentYear-3)+"",Name:""+parseInt(currentYear-3)+""},
			{Code:""+parseInt(currentYear-4)+"",Name:""+parseInt(currentYear-4)+""},
			{Code:""+parseInt(currentYear-5)+"",Name:""+parseInt(currentYear-5)+""}
		];
		$('#span_pd_year').combo({
			data:data,
			value: 'Code',
			text: 'Name',
			width :206,
			height:80,
			listId:'',
			defaultSelected: 0,
			editable: false,
			callback:{
				onChange: function(data){
					$("#pd_year").val(data.Code);
				}
			}
		}).getCombo();
	},
	initGrid:function(){
		var type = $("#type").val();
		var codeLabel = '';
		var nameLabel = '';
		var codeHidden = false;
		switch(type){
			case 'brand' : 
				codeLabel = '品牌编号';
				nameLabel = '品牌名称';
				break ;
			case 'type' : 
				codeLabel = '类别编号';
				nameLabel = '类别名称';
				break ;
			case 'year' : 
				nameLabel = '年份';
				codeHidden = true;
				break ;
			case 'season' : 
				nameLabel = '季节';
				codeHidden = true;
				break ;
			default :
				break ;
		}
		var colModel = [
	    	{label:codeLabel,name: 'code',index:'code',width:60,hidden:codeHidden},	
	    	{label:nameLabel,name: 'name',index:'name',width:80},	
        	{label:'库存数量',name: 'amount',index:'amount',width:70, align:'right'},	
        	{label:'占比(%)',name: 'amount_proportion',index:'',width:60, align:'right'},
        	{label:'成本金额',name: 'cost_money',index:'cost_money',width:80, align:'right',formatter: PriceLimit.formatMoney},	
        	{label:'占比(%)',name: 'costmoney_proportion',index:'',width:60, align:'right'},
        	{label:'零售金额',name: 'sell_money',index:'sell_money',width:80, align:'right',formatter: PriceLimit.formatMoney},	
	    	{label:'占比(%)',name: 'sellmoney_proportion',index:'',width:60, align:'right'}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'local',
			width: 630,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:false,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			userDataOnFooter: true,
			jsonReader: {
				root: 'data',
				repeatitems : false,
				id: 'code'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.gridTotal();
				document.getElementById("container").style.width = ($(window).width()-680) + "px";
				THISPAGE.buildChart();
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	gridTotal:function(){
    	var grid = $('#grid');
		var footerData = {code:'合计'};	
		footerData["amount"] = grid.getCol("amount",false,'sum');
		footerData["cost_money"] = grid.getCol("cost_money",false,'sum');
		footerData["sell_money"] = grid.getCol("sell_money",false,'sum');
		grid.footerData('set',footerData);
		var ids = $("#grid").getDataIDs();
		for(var i=0;i < ids.length;i++){
			var rowData = $("#grid").jqGrid("getRowData", ids[i]);
			var proportion = {};
			if(footerData.amount != 0){
				proportion.amount_proportion = PriceLimit.formatMoney(rowData.amount/footerData.amount*100);
			}
			if(footerData.cost_money != 0){
				proportion.costmoney_proportion = PriceLimit.formatMoney(rowData.cost_money/footerData.cost_money*100);
			}
			if(footerData.sell_money != 0){
				proportion.sellmoney_proportion = PriceLimit.formatMoney(rowData.sell_money/footerData.sell_money*100);
			}
			$("#grid").jqGrid('setRowData', ids[i], proportion);
		}
    },
    buildChart:function(){
    	var ids = $("#grid").getDataIDs();
    	var chartjs = '';
    	chartjs += '{';
    	chartjs += '"chart":{"type":"pie","options3d":{"enabled":true,"alpha":45}},';
    	chartjs += '"title":{"text":"';
    	var type = $("#type").val();
		switch(type){
			case 'brand' : 
				chartjs += '品牌库存分析';
				break ;
			case 'type' : 
				chartjs += '类别库存分析';
				break ;
			case 'year' : 
				chartjs += '年份库存分析';
				break ;
			case 'season' : 
				chartjs += '季节库存分析';
				break ;
			default :
				break ;
		}
    	chartjs += '"},';
    	chartjs += '"plotOptions":{"pie":{"innerSize":100,"depth":45}},';
    	chartjs += '"series":[{';
    	chartjs += '"name":"库存金额",';
    	chartjs += '"data":[';
    	var dataCount = 0;
    	for(var i=0;i < ids.length;i++){
    		var rowData = $("#grid").jqGrid("getRowData", ids[i]);
			if(parseFloat(rowData.cost_money) <= 0){
				continue;
			}
			chartjs += '[';
			chartjs += '"'+rowData.name+'",';
			chartjs += PriceLimit.formatMoney(rowData.cost_money);
			chartjs += '],';
			dataCount++;
		}
    	if(dataCount > 0){
    		chartjs = chartjs.substring(0, chartjs.length-1);
    	}
    	chartjs += ']}]';
    	chartjs += '}';
    	
    	eval("$('#container').highcharts("+chartjs+")");
    },
	buildParams : function(){
		var params = '';
		params += 'type='+$("#type").val();
		params += '&depot_code='+$("#depot_code").val();
		params += '&bd_code='+$("#bd_code").val();
		params += '&tp_code='+$("#tp_code").val();
		params += '&pd_season='+$("#pd_season").val();
		params += '&pd_year='+$("#pd_year").val();
		params += '&pd_code='+$("#pd_code").val();
		return params;
	},
	reset:function(){
		$("#pd_code").val("");
		$("#pd_name").val("");
		$("#depot_name").val("");
		$("#depot_code").val("");
		$("#bd_name").val("");
		$("#bd_code").val("");
		$("#tp_name").val("");
		$("#tp_code").val("");
		$("#span_pd_season").getCombo().selectByValue("");
		$("#span_pd_year").getCombo().selectByValue("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
	}
}
THISPAGE.init();